package com.pm.controller;

import com.pm.entity.Task;
import com.pm.entity.User;
import com.pm.service.TaskService;
import com.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务管理控制器
 */
@RestController
@RequestMapping("/api/tasks")
@CrossOrigin(origins = "*")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有任务
     */
    @GetMapping
    public ResponseEntity<List<Task>> getAllTasks() {
        List<Task> tasks = taskService.getAllTasks();
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据ID获取任务
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getTaskById(@PathVariable String id) {
        try {
            Task task = taskService.findById(id);
            if (task == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "任务不存在");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(task);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取任务信息失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 创建任务
     */
    @PostMapping
    public ResponseEntity<?> createTask(@RequestBody Task task, Authentication authentication) {
        try {
            // 设置任务创建者为当前用户
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            task.setCreatorId(currentUser.getId());
            
            Task createdTask = taskService.createTask(task);
            
            Map<String, Object> response = new HashMap<>();
            response.put("task", createdTask);
            response.put("message", "任务创建成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable String id, @RequestBody Task task, Authentication authentication) {
        try {
            // 检查权限：只有任务创建者或分配人可以更新任务
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Task existingTask = taskService.findById(id);
            
            if (existingTask == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "任务不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean canUpdate = existingTask.getCreatorId().equals(currentUser.getId()) ||
                              (existingTask.getAssigneeId() != null && existingTask.getAssigneeId().equals(currentUser.getId()));
            
            if (!canUpdate) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此任务");
                return ResponseEntity.badRequest().body(error);
            }
            
            task.setId(id);
            task.setCreatorId(existingTask.getCreatorId()); // 保持原创建者
            Task updatedTask = taskService.updateTask(task);
            
            Map<String, Object> response = new HashMap<>();
            response.put("task", updatedTask);
            response.put("message", "任务更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：只有任务创建者可以删除任务
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Task existingTask = taskService.findById(id);
            
            if (existingTask == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "任务不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingTask.getCreatorId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限删除此任务");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean deleted = taskService.deleteTask(id);
            if (!deleted) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "删除任务失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "任务删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "删除任务失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 根据项目ID获取任务
     */
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<Task>> getTasksByProjectId(@PathVariable String projectId) {
        List<Task> tasks = taskService.findByProjectId(projectId);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 获取分配给我的任务
     */
    @GetMapping("/assigned-to-me")
    public ResponseEntity<List<Task>> getMyAssignedTasks(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<Task> tasks = taskService.findByAssigneeId(currentUser.getId());
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 获取我创建的任务
     */
    @GetMapping("/created-by-me")
    public ResponseEntity<List<Task>> getMyCreatedTasks(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<Task> tasks = taskService.findByCreatorId(currentUser.getId());
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 根据状态获取任务
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<Task>> getTasksByStatus(@PathVariable String status) {
        List<Task> tasks = taskService.findByStatus(status);
        return ResponseEntity.ok(tasks);
    }
    
    /**
     * 更新任务状态
     */
    @PatchMapping("/{id}/status")
    public ResponseEntity<?> updateTaskStatus(@PathVariable String id, @RequestBody Map<String, String> request, Authentication authentication) {
        try {
            // 检查权限：任务创建者或分配人可以更新状态
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Task existingTask = taskService.findById(id);
            
            if (existingTask == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "任务不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean canUpdate = existingTask.getCreatorId().equals(currentUser.getId()) ||
                              (existingTask.getAssigneeId() != null && existingTask.getAssigneeId().equals(currentUser.getId()));
            
            if (!canUpdate) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此任务状态");
                return ResponseEntity.badRequest().body(error);
            }
            
            String status = request.get("status");
            boolean updated = taskService.updateTaskStatus(id, status);
            
            if (!updated) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "更新任务状态失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "任务状态更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 分配任务
     */
    @PatchMapping("/{id}/assign")
    public ResponseEntity<?> assignTask(@PathVariable String id, @RequestBody Map<String, String> request, Authentication authentication) {
        try {
            // 检查权限：只有任务创建者可以分配任务
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            Task existingTask = taskService.findById(id);
            
            if (existingTask == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "任务不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingTask.getCreatorId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限分配此任务");
                return ResponseEntity.badRequest().body(error);
            }
            
            String assigneeId = request.get("assigneeId");
            boolean assigned = taskService.assignTask(id, assigneeId);
            
            if (!assigned) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "分配任务失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "任务分配成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}